package com.webemail.email.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.webemail.email.entity.Email;
import com.webemail.email.mapper.EmailMapper;
import com.webemail.email.service.MyEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

/**
 * @author LaiHQ
 */
@Service
public class MyEmailServiceImpl extends ServiceImpl<EmailMapper,Email> implements MyEmailService {

    @Autowired
    private EmailMapper emailMapper;

    /**
     * 同步邮件到系统
     *
     * @param folder
     * @param folderFullName
     * @param currAccount
     */
    @Override
    public void syncEmail(Long folderId,Folder folder,String folderFullName, String currAccount) {
        Long lastUid = emailMapper.selectLastUid(currAccount, folderFullName);
        UIDFolder uidFolder = (UIDFolder) folder;
        try {
            List<Email> list = new ArrayList<>();
            if(ObjectUtil.isEmpty(lastUid)){
                if(!folder.isOpen()){
                    folder.open(Folder.READ_WRITE);
                }
                Message[] messages = folder.getMessages();
                parseMessage(folderId,list,messages,folderFullName,currAccount,uidFolder);
            }else{
                if(!folder.isOpen()){
                    folder.open(Folder.READ_WRITE);
                }
                Message[] messages = uidFolder.getMessagesByUID(lastUid+1, Long.MAX_VALUE);
                parseMessage(folderId,list,messages,folderFullName,currAccount,uidFolder);
            }
            this.saveBatch(list);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取某文件夹下的所有邮件
     *
     * @param fullName    文件夹完整名
     * @param currAccount 当前邮箱账户
     * @return
     */
    @Override
    public List<Email> getEmailByFolder(String fullName, String currAccount) {
        List<Email> list = this.list(Wrappers.lambdaQuery(Email.class)
                .eq(Email::getFolderFullName, fullName)
                .eq(Email::getCurrAccount, currAccount));
        return list;
    }



    /**
     * 解析Message格式信息为系统的Email格式
     * @param list
     * @param messages
     * @param folderFullName
     * @param currAccount
     * @param uidFolder
     * @throws MessagingException
     */
    private void parseMessage(Long folderId,List<Email> list,Message[] messages,String folderFullName
            ,String currAccount,UIDFolder uidFolder) throws MessagingException {
        for(Message message:messages){
            Email email = new Email();
            email.setCreateUser("1");
            email.setCreateTime(new Date().toString());
            email.setFolderId(folderId);
            email.setFolderFullName(folderFullName);
            //当前账户
            email.setCurrAccount(currAccount);
            //发件人
            email.setSendAccount(message.getFrom()[0].toString());
            //收件人
            Address[] recipients = message.getRecipients(Message.RecipientType.TO);
            StringJoiner reAccounts = new StringJoiner(",");
            for(Address address:recipients){
                reAccounts.add(address.toString());
            }
            email.setReceiveAccount(reAccounts.toString());
            //抄送人
            Address[] copys = message.getRecipients(Message.RecipientType.CC);
            if(ObjectUtil.isNotEmpty(copys)){
                StringJoiner copyAccounts = new StringJoiner(",");
                for(Address address:copys){
                    copyAccounts.add(address.toString());
                }
                email.setCopyAccount(copyAccounts.toString());
            }
            if(ObjectUtil.isNotEmpty(message.getHeader("Message-ID"))){
                email.setMessageId(message.getHeader("Message-ID")[0]
                        .replaceAll("[<>]", ""));
            }
            email.setUid(uidFolder.getUID(message));
            email.setTitle(message.getSubject());
            try{
                Object content = message.getContent();
                if(content instanceof String){
                    email.setContent((String) content);
                }else if(content instanceof Multipart){
                    // 处理多部分内容（HTML+附件等）
                    Multipart multipart = (Multipart) content;
                    for (int i = 0; i < multipart.getCount(); i++) {
                        BodyPart bodyPart = multipart.getBodyPart(i);
                        if (bodyPart.isMimeType("text/plain")) {
                            String textContent = (String) bodyPart.getContent();
                            email.setContent(textContent);
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            list.add(email);
        }
    }

}
